<template>
  <Container class="voucher-product">
    <div slot="header" class="container-header title title-center">满额返劵
      <Button
        size="large"
        class="fl btn-back"
        icon="ios-arrow-back"
        @click="jumpPrevPage"
      >返回</Button>
    </div>
    <DefaultEditItem
      ref="fullReturnForm"
      :set-disabled="!isSave"
      :form="$store.state.fullReturnSale.FullreturnForm"
      :rules="rules"
    />
    <div slot="footer" class="container-footer bg-white">
      <Button v-if="!type && isSave" type="primary" size="large" class="ml" @click="onShowList">保存</Button>
      <Button v-if="!isSave" type="primary" size="large" class="ml" @click="onJoinNextPage">下一步</Button>
    </div>
    <Loader :status="status" @refresh="getDetailData" />
  </Container>
</template>
<script>
import DefaultEditItem from './edit/DefaultEditItem'
import { getValue, getValue1 } from './edit/SaleListMethods'
import { mapGetters } from 'vuex'
export default {
  name: 'fullReturnRules',
  components: {
    DefaultEditItem
  },
  data () {
    return {
      id: this.$route.query.id || '',
      type: this.$route.query.type || '',
      isEmpty: false, // 是否清空数据
      isSave: true, // 是否保存数据
      rules: {
        name: [{ required: true, message: '请输入促销名称', trigger: 'blur' }],
        grade: [{ required: true, type: 'array', min: 1, message: '请选择活动对象', trigger: 'change' }],
        date: [
          {
            required: true,
            message: '请开始时间',
            trigger: 'change',
            type: 'array'
            // fields: {
            //   0: { type: "date", required: true, message: "请输入起止日期" },
            //   1: { type: "date", required: true, message: "请输入起止日期" }
            // }
          }
        ],
        remarks: [
          { message: '请输入活动备注', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请输入促销类型', trigger: 'change' }
        ],
        endTime: [
          {
            required: true,
            validator: this.validateendTime,
            trigger: 'change'
            // type: "array"
          }
        ],
        time: [
          { required: true, message: '请输入时间', trigger: 'blur' },
          { validator: this.validatetime, trigger: 'blur' }
        ]
      },
      status: 'pass'
    }
  },
  computed: {
    ...mapGetters([
      'getReturnGender',
      'getReturnTimeList',
      'limitReturnCompleteDate',
      'getReturnType',
      'getGiftCouponRuleList',
      'getGiftJoinType',
      'getGiftParamGrade'
    ])
    // productSkuList () {
    //   return getPuduct(this.$store.state.fullReturnSale.GetsaleData, {
    //     child: 'productSkuList',
    //     getParam: ['productId', 'id', 'parentcode', 'code']
    //   })
    // }
  },
  methods: {
    getDetailData () {
      this.status = 'loading'
      this.$store.dispatch('getGiftDetailData', this.id).then(res => {
        this.status = 'pass'
      })
    },
    validateendTime (rule, value, callback) {
      let realSeven = ''
      realSeven = this.$store.state.fullReturnSale.FullreturnForm.date[1] && new Date(new Date(this.$store.state.fullReturnSale.FullreturnForm.date[1]).getTime() + 24 * 7 * 60 * 60 * 1000)
      if (!value) {
        return callback(new Error('请输入订单完成时间'))
      } else if (value <= realSeven) {
        return callback(new Error('完成订单时间必须在下单结束时间7天后'))
      } else {
        callback()
      }
    },
    validatetime (rule, value, callback) {
      if (!/^([0-7])$/.test(value)) {
        return callback(new Error('范围是0-7天'))
      } else {
        callback()
      }
    },
    jumpPrevPage () {
      this.$router.back()
    },
    onShowList () {
      let url = { name: 'sales/fullReturn/list', query: {} }
      let urlJson = '/activity/full_gift_coupon/save_base'
      let param = {
        fullGiftCouponDetailDTO: {
          activityFullGiftCouponDTO: {
            fullGiftCouponTypeEnum: this.getReturnType, // 满额返券形式
            isFirstOrderGift: this.getReturnGender, //是否仅首次首单返券
            limitCompleteDatetime: this.limitReturnCompleteDate, //用户在之前完成订单
            limitReturnDate: this.$store.state.fullReturnSale.FullreturnForm.time // 天内，未申请退款
          },
          activityInfoDTO: {
            activityName: this.$store.state.fullReturnSale.FullreturnForm.name, //活动名称
            startDate: this.getReturnTimeList[0].startDatetime,
            endDate: this.getReturnTimeList[0].endDatetime,
            shelfStatusEnum: 'ON',
            activityDescription: this.$store.state.fullReturnSale.FullreturnForm.remarks, //活动备注
            joinTypeEnum: this.getGiftJoinType,
            storeTypeEnumList: this.getGiftParamGrade //活动对象
          }
        }
      }
      if (this.getReturnType == 'PRODUCT') { // 新增的订单超多少商品的
        param.fullGiftCouponDetailDTO.activityFullGiftCouponDTO.giftCouponRuleList = this.getGiftCouponRuleList
      } else { // 正常满额返券
        param.couponInfoDTOList = getValue1(
          this.$store.state.fullReturnSale.FullreturnForm.activityGiftCouponList,
          {
            index1: 'denomination',
            index2: 'useCondition',
            index3: 'validityDays',
            index4: 'custom'
          }
        ) //优惠劵
        param.fullGiftCouponDetailDTO.activityFullGiftCouponDTO.giftCouponRuleList = getValue(
          this.$store.state.fullReturnSale.FullreturnForm.activityGiftCouponList,
          {
            index: 'value',
            index1: 'isParcel'
          }
        )
      }
      this.$refs['fullReturnForm'].$refs['form'].validate(valid => {
        if (valid) {
          let status = false
          for (let item of this.$store.state.fullReturnSale.FullreturnForm.activityGiftCouponList) {
            if (!item.useCondition) {
              status = true
            }
          }
          if (this.getReturnType == '2' && status) {
            this.$Message.error('请创建优惠劵!')
            return false
          }
          this.status = 'loading'
          this.$jsonPost(urlJson, param).then(data => {
            url.query.id = data
            this.status = 'pass'
            this.$Message.success('保存成功!')
            if (!this.type) this.$router.replace({ name: 'sales/fullReturn/rules', query: { id: data } })
            this.$router.push(url)
          }).catch(data => {
            this.status = 'pass'
          })
        }
      })
    },
    onJoinNextPage () {
      this.$router.push({ name: 'sales/fullReturn/list', query: { id: this.id } })
    }
  },
  beforeRouteEnter (to, from, next) {
    /*
      1. 路由从不是下一页进入的都清空
      2. 路由从下一页进入并且有id就不刷新接口--保存信息
    */
    next(vm => {
      if (from.name !== 'sales/fullReturn/list') {
        vm.isEmpty = true
      } else {
        vm.isSave = false
      }
      if (vm.isEmpty) vm.$store.commit('setFullreturnSaleEmpty')
      if (vm.id && vm.isSave) vm.getDetailData()
    })
  }

}
</script>

